package com.syt.cellphone.information.ui.main.phone

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import com.google.android.material.tabs.TabLayout
import com.syt.cellphone.information.App
import com.syt.cellphone.information.R
import com.syt.cellphone.information.base.VMBaseFragment
import com.syt.cellphone.information.constant.AppConst
import com.syt.cellphone.information.constant.PreferKey
import com.syt.cellphone.information.data.pojo.PhoneGroup
import com.syt.cellphone.information.lib.theme.ATH
import com.syt.cellphone.information.lib.theme.accentColor
import com.syt.cellphone.information.ui.main.MainViewModel
import com.syt.cellphone.information.ui.main.phone.groups.GroupPhoneFragment
import com.syt.cellphone.information.ui.search.SearchActivity
import com.syt.cellphone.information.utils.getViewModel
import com.syt.cellphone.information.utils.getViewModelOfActivity
import com.syt.cellphone.information.utils.putPrefInt
import com.syt.cellphone.information.utils.startActivity
import kotlinx.android.synthetic.main.fragment_phone.*
import kotlinx.android.synthetic.main.view_tab_layout_min.*
import kotlinx.android.synthetic.main.view_title_bar.*
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jetbrains.anko.toast

/**
 *  @author: syt
 *  创建时间: 2020/8/24 17:08
 *  @功能   手机碎片
 *  @version v1.0
 */
class PhoneFragment : VMBaseFragment<PhoneViewModel>(R.layout.fragment_phone),
    TabLayout.OnTabSelectedListener {

    override val viewModel: PhoneViewModel
        get() = getViewModel(PhoneViewModel::class.java)
    private val activityViewModel: MainViewModel
        get() = getViewModelOfActivity(MainViewModel::class.java)

    private var phoneGroupLiveData: LiveData<List<PhoneGroup>>? = null
    private val phoneGroups = mutableListOf<PhoneGroup>()
    private val fragmentMap = hashMapOf<Int, GroupPhoneFragment>()

    override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {
        setSupportToolbar(toolbar)
        initView()
        initPhoneGroupData()
    }

    override fun onCompatCreateOptionsMenu(menu: Menu) {
        menuInflater.inflate(R.menu.main_phone_title, menu)
    }

    override fun onCompatOptionsItemSelected(item: MenuItem) {
        super.onCompatOptionsItemSelected(item)
        when (item.itemId) {
            R.id.menu_search -> startActivity<SearchActivity>()
            R.id.menu_brand_admin -> activity?.toast("品牌管理")
            R.id.menu_update_toc -> activity?.toast("更新数据")
        }
    }

    // 加载视图
    private fun initView() {
        // 设置底部线条颜色，利用反射.
        ATH.applyEdgeEffectColor(view_pager_phone)
        // 宽度自动关闭
        tab_layout.isTabIndicatorFullWidth = false
        // 可以滚动
        tab_layout.tabMode = TabLayout.MODE_SCROLLABLE
        // 设置光标颜色
        tab_layout.setSelectedTabIndicatorColor(requireContext().accentColor)
        // 设置viewpager
        tab_layout.setupWithViewPager(view_pager_phone)
        // 保存相邻数量
        view_pager_phone.offscreenPageLimit = 1
        // 设置适配器
        view_pager_phone.adapter = TabFragmentPageAdapter(childFragmentManager)
    }

    // 加载分组数据
    private fun initPhoneGroupData() {
        // 删除观察者
        phoneGroupLiveData?.removeObservers(viewLifecycleOwner)
        phoneGroupLiveData = App.db.phoneGroupDao().liveDataAll()
        phoneGroupLiveData?.observe(viewLifecycleOwner, Observer {
            viewModel.checkGroup(it)
            launch {
                synchronized(this) {
                    tab_layout.removeOnTabSelectedListener(this@PhoneFragment)
                }
                var noGroupSize = 0

                withContext(IO) {

                }

                synchronized(this@PhoneFragment) {
                    phoneGroups.clear()
                    phoneGroups.add(0, AppConst.phoneGroupAll)
                    phoneGroups.add(1, AppConst.phoneGroupUpdate)
                    view_pager_phone.adapter?.notifyDataSetChanged()
                }
            }
        })
    }

    override fun onTabReselected(tab: TabLayout.Tab?) = Unit

    override fun onTabUnselected(tab: TabLayout.Tab?) = Unit

    override fun onTabSelected(tab: TabLayout.Tab?) {
        tab?.position?.let {
            putPrefInt(PreferKey.saveTabPosition, it)
        }
    }

    fun gotoTop() {
        fragmentMap[phoneGroups[view_pager_phone.currentItem].groupId]?.gotoTop()
    }

    // 适配器
    private inner class TabFragmentPageAdapter internal constructor(fm: FragmentManager)
        : FragmentStatePagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT){

        override fun getPageTitle(position: Int): CharSequence? {
            return phoneGroups[position].groupName
        }

        override fun getItem(position: Int): Fragment {
            val group = phoneGroups[position]
            var fragment =  fragmentMap[group.groupId]
            if (fragment == null) {
                fragment = GroupPhoneFragment.newInstance(position, group.groupId)
                fragmentMap[group.groupId] = fragment
            }
            return fragment
        }

        override fun getCount(): Int {
            return phoneGroups.size
        }

    }
}